package com.aiti.lulian.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.service.ISmsCodeService;
import com.aiti.lulian.utils.SmsCompont;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SmsCodeServiceImpl
 * @Description
 * @Author diaozhende
 * @Date 2024/6/21 21:22
 */
@Service
@Slf4j
public class SmsCodeServiceImpl implements ISmsCodeService {

    @Value("${aliyun.sms.template}")
    private String smsTemplateId = "SMS_465960892";
    /** 短信验证码过期时间 */
    private static final long CODE_EXPIRED = 1000 * 60 * 5;
    public static final String CHECK_CODE_KEY = "sms:%s:%s";
    public enum SendCodeEnum {
        USER_LOGIN;
    }


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SmsCompont smsCompont;

    /**
     * 校验验证码
     *
     * @param codeData 请求参数{code: "", phone: ""}
     * @return void
     * @date 2024/6/21 21:33
     * @author diaozhende
     */
    @Override
    public void verifyCode(String codeData) {
        String code = JSONObject.parseObject(codeData).getString("code");
        String phone = JSONObject.parseObject(codeData).getString("phone");
        //构建RedisKey
        String key = String.format(CHECK_CODE_KEY, phone, phone);
        String captchaRedis = stringRedisTemplate.opsForValue().get(key);
        //取出Redis中的验证码
        if(StrUtil.isEmpty(captchaRedis)){
            throw new RuntimeException("验证码已过期!");
          //  return Message.fail("登陆失败，验证码已过期！");
        }
        String captcha = captchaRedis.split("_")[0];
        if(!code.equals(captcha)){
            throw new RuntimeException("验证码错误！");
           // return Message.fail("登陆失败，验证码错误！");
        }
    }


    /**
     * 发送验证码
     * @param parameters 请求参数{phone: ""}
     * @return void
     * @date 2024/6/21 21:37
     * @author diaozhende
     */
    @Override
    public void sendCode(JSONObject parameters) {
        String phone = parameters.getString("phone");
        //构建RedisKey
        String key = String.format(CHECK_CODE_KEY, phone, phone);
        String captcha = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(captcha)){
            long ttl = Long.parseLong(captcha.split("_")[1]);
            long currentTimestamp = System.currentTimeMillis();
            long leftTime = currentTimestamp - ttl;
            if(leftTime < (1000 * 60 * 5)){
                log.warn("重复发送短信验证码过于频繁，时间间隔:{}",leftTime);
                throw new RuntimeException("重复发送短信验证码过于频繁,请稍后再试");
            }
        }

        int code = RandomUtil.randomInt(100000, 999999);
        String codeValue = code + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(key, codeValue, CODE_EXPIRED, TimeUnit.MILLISECONDS);
        boolean isSuccess = smsCompont.send(phone, smsTemplateId, String.valueOf(code));

        if(!isSuccess)
            throw new RuntimeException("短信发送失败，请联系管理员");
        // return isSuccess ? Message.success("短信可能会存在延迟，请耐心等待") : Message.fail("短信发送失败，请联系管理员");
    }
}
